package com.tmt.spring.validation;

import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.util.StringUtils;

import javax.activation.MimeType;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class EmailHelper {

    /**
     * 发送Html内容的邮件
     * @param host 指定邮件服务器，例如："smtp.qq.com"
     * @param from 发送邮件地址
     * @param authCode 邮件服务器赋予发送邮箱的授权码
     * @param to   接收邮件地址
     * @param subject 邮件标题
     * @param content 邮件HTML内容
     * @return
     */
    public static boolean sendHtmlEmail(String host, String from, String authCode,
                                        String to, String subject, String content){
        try{
            // 获取系统属性
            Properties properties = System.getProperties();

            // 设置邮件服务器
            properties.setProperty("mail.smtp.host", host);

            Session session = Session.getDefaultInstance(properties);
            if (!StringUtils.isEmpty(authCode)) {
                properties.put("mail.smtp.auth", "true");
                MailSSLSocketFactory sf = new MailSSLSocketFactory();
                sf.setTrustAllHosts(true);
                properties.put("mail.smtp.ssl.enable", "true");
                properties.put("mail.smtp.ssl.socketFactory", sf);
                // 获取默认session对象
                session = StringUtils.isEmpty(authCode) ? Session.getDefaultInstance(properties)
                        : Session.getInstance(properties, new Authenticator() {
                    public PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(from, authCode);
                    }
                });
            }

            // 创建默认的 MimeMessage 对象。
            MimeMessage message = new MimeMessage(session);

            // Set From: 头部头字段
            message.setFrom(new InternetAddress(from));

            // Set To: 头部头字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

            // Set Subject: 头字段
            message.setSubject(subject);

            // 发送 HTML 消息, 可以插入html标签
            message.setContent(content, "text/html;charset=utf-8" );

            // 发送消息
            Transport.send(message);
            return true;
        }catch (Exception mex) {
            mex.printStackTrace();
        }

        return false;
    }

    /*public static void main(String[] args){
        sendHtmlEmail("smtp.sina.com","sichuanwuyi@sina.com", "750929","10692081@qq.com",
                "TMT邮箱验证","<a href='http://localhost:8080/s/email/validate/confirm?sid=123&code=345'>点击完成邮箱确认</a>");
    }*/
}
